from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from staff.models import *
from utils.sendemail import EmailTool
from rest_framework import status

# Create your views here.
class Sends(APIView):
    def post(self,request):
        try:
            staff_id1 = request.data.get("staff_id1")
            staff_id2 = request.data.get("staff_id2")
            content = request.data.get("content")
            email1 = StaffModel.objects.get(id=staff_id1).email
            email2 = StaffModel.objects.get(id=staff_id2).email
            # email2 = "3461736320@qq.com"
            miyao = "vcxvaasaqgcxdjca"#发送者qq邮箱密钥

            et = EmailTool(email1,miyao)
            et.sendmail(email2,content)
            Emails.objects.create(content=content,send_id=staff_id1,reception_id=staff_id2)
            return Response({"msg":"发送成功"})
        except Exception as e:
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR,"msg":e})

    def get(self,request):
        staff = request.session.get("staff")
        emails = Emails.objects.filter(reception_id=staff['id']).all()
        staff = StaffModel.objects.get(id=staff['id'])
        send_name = staff.name
        email_list = []
        for i in emails:
            reception_name = StaffModel.objects.get(id=i.reception_id).name
            data = {
                "send_name":send_name,
                "reception_name":reception_name,
                "content":i.content,
                "time":str(i.create_time).split(".")[0]
            }
            email_list.append(data)
        return Response({"code":status.HTTP_200_OK,"msg":"获取所有邮件成功","emails":email_list})